<template>
    <div class = "staff-management-box">

        <div class = "header-box">
            <el-select v-model="selectStaffObj.classNum" placeholder="请选择工班" clearable filterable style = "min-width: 200px;">
                <el-option v-for="position in classList"
                           :label="position.className"
                           :value="position.classId" />
            </el-select>
            <el-input v-model="selectStaffObj.nameOrNum" placeholder="请输入名字或工号" clearable/>
            <el-button @click = "selectStaffBtnClick">
                查询&nbsp;&nbsp;<i class="fa fa-search" aria-hidden="true"></i>
            </el-button>
            <div class="left">
                <el-button @click = "addStaffBtnClick">添加员工&nbsp;&nbsp;<i class="fa fa-user-plus" aria-hidden="true"></i></el-button>
                <el-button @click = "exportExcel">导出表格&nbsp;&nbsp;<i class="fa fa-floppy-o" aria-hidden="true"></i></el-button>
            </div>
        </div>
        <div class = "center-box">
            <el-table :data="peopleInfoList"
                      border style="width: 100%"
                      v-loading="loading"
            >
                <el-table-column type="index" width="77" />
                <el-table-column prop="peopleNum" sortable label="工号" />
                <el-table-column prop="peopleName" sortable label="姓名" />
                <el-table-column prop="positionName" sortable label="职务" />
                <el-table-column prop="className" sortable label="工班" />
                <el-table-column prop="amount3" label="操作" v-if = "staffInfo.jurisdiction>1" >
                    <template #default="scope">
                        <el-link type="primary" @click = "changeStaffClassBtnClick(scope.row)">
                            编辑&nbsp;
                            <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                        </el-link>
                        <el-link type="danger" @click = "deleteStaffBtnClick(scope.row)">
                            删除&nbsp;
                            <i class="fa fa-trash-o" aria-hidden="true"></i>
                        </el-link>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!--    分页暂时没做-->
        <div class='page-box'>
            <el-pagination
                background
                small
                layout="prev, pager, next"
                :page-size="10"
                :total.sync="thePage.totalPage"
                :current-page.sync="thePage.currentPage"
                @current-change=""
                :hide-on-single-page="true"
            >
            </el-pagination>
        </div>
<!--    编辑和添加员工用的弹出框-->
        <el-dialog v-model="addStaffDialogVisible" :title="modeStr[modeIndex]">
            <el-form
                ref="ruleFormRef"
                :model="formData"
                :rules="rules"
            >
                <el-form-item label="工号" prop="peopleNum" :label-width="formLabelWidth">
                    <el-input v-model="formData.peopleNum" :disabled = "modeIndex !== modeEnum.addMode"/>
                </el-form-item>
                <el-form-item label="姓名" prop="peopleName" :label-width="formLabelWidth">
                    <el-input v-model="formData.peopleName" :disabled = "modeIndex !== modeEnum.addMode"/>
                </el-form-item>
                <el-form-item label="职务" prop="position" :label-width="formLabelWidth">
                    <el-select v-model="formData.position" placeholder="请选择职务" filterable>
                        <el-option v-for="position in positionList"
                                   :label="position.positionName"
                                   :value="position.positionId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="工班" prop="classNum" :label-width="formLabelWidth">
                    <el-select v-model="formData.classNum" placeholder="请选择工班" filterable>
                        <el-option v-for="position in classList"
                                   :label="position.className"
                                   :value="position.classId" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                <el-button @click="addStaffDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmBtnClick(ruleFormRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>



    </div>
</template>

<script setup>
import {
    addPeople,
    selectPeople,
    updatePeople,
    delectPeople,
} from "../api";
import {computed, ref, reactive, watch, onMounted} from "vue";
import store from "../store";
import {debounce} from "lodash";
import * as XLSX from "xlsx";
import FileSaver from 'file-saver'

let staffInfo = computed(()=>{
    return store.state.staffInfo;
})
let positionList = computed(()=>{
    return store.state.positionList;
})

let classList = computed(()=>{
    if(staffInfo.value.jurisdiction > 1){
        return store.state.classList;
    }else
    {
        return [{
            className: staffInfo.value.userName,
            classId: staffInfo.value.userNum
        }]
    }
});

//初始化
onMounted(()=>{
    selectStaffBtnClick();
})
let thePage = reactive({
    currentPage: 1,
    totalPage: 1,
    limPage:200,
});
let addStaffDialogVisible = ref(false);
//当前的员工数据
let formData = reactive( {
        id:-1,
        peopleNum: "",
        peopleName: "",
        position: "",
        classNum: ""
    });

const modeStr =  reactive(['添加员工','编辑员工']);
const modeEnum = reactive({
    addMode:0,
    changeMode:1,
});
let modeIndex = ref(0);

function exportExcel(){
    let data = [];
    peopleInfoList.forEach((staff,i)=>{
        data.push([
            i+1,
            staff.peopleNum,
            staff.peopleName,
            staff.positionName,
            staff.className
        ]);
    })
    // console.log(data);

    let newSheet  = XLSX.utils.aoa_to_sheet(data);
    const newBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(newBook, newSheet, 'sheet1');
    var wopts = {
        bookType: 'xlsx',
        bookSST: false,
        type: 'array'
    };
    var wbout = XLSX.write(newBook, wopts);
    try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '人员信息表.xlsx')
    } catch (e) {
        if (typeof console !== 'undefined') {
            console.log(e, wbout)
        }
    }
}

let selectStaffObj = reactive({
    nameOrNum:"",
    classNum: "",
    page: 1,
    lim: thePage.limPage,
    centerId: staffInfo.value.centerId,
})

let peopleInfoList = reactive([]);

function deleteStaffBtnClick(staff){
    ElMessageBox.confirm(
            `此操作不可逆,确定要将【${staff.peopleName}】移除吗?`,"警告"
        ).then(async () => {
            let data = {
                id:staff.id
            };
            delectPeople(data).then((res) => {
                if(res.code === 200){
                    ElNotification({
                        title: 'OK!',
                        message: '删除成功',
                        duration: 1000,
                        position: 'bottom-right',
                        type: 'success',
                    });
                    peopleInfoList.splice(peopleInfoList.indexOf(staff),1);
                }else{
                    console.log(res);
                }
            },(error)=>{
                console.log(error);
            });
        }).catch((err) => {
        console.log(err)
    })
}

const ruleFormRef = ref(null);
const rules = reactive({
    peopleNum: [{required: true, message: '不能为空!', trigger: 'blur',}],
    peopleName: [{ required: true, message: '不能为空!', trigger: 'blur' }],
    position: [{ required: true, message: '不能为空!', trigger: 'blur' }],
    classNum:[{ required: true, message: '不能为空!', trigger: 'blur' }],
});

//编辑员工
function changeStaffClassBtnClick(staff){
    modeIndex.value = modeEnum.changeMode;
    formData.id = staff.id;
    formData.peopleName = staff.peopleName;
    formData.peopleNum = staff.peopleNum;
    formData.position = staff.positionId;
    formData.classNum = staff.classId;
    addStaffDialogVisible.value = true;
    if(ruleFormRef.value)
        ruleFormRef.value.clearValidate();
}

//添加模式
function addStaffBtnClick(){
    modeIndex.value = modeEnum.addMode;
    addStaffDialogVisible.value = true
    if(ruleFormRef.value)
        ruleFormRef.value.clearValidate();
}

const confirmBtnClick = async (formEl) => {
    if (!formEl) return;
    try {
        await formEl.validate((valid, fields) => {
            console.log(fields)
            if (valid) {
                console.log(formData);
                switch (modeIndex.value){
                    case modeEnum.addMode:
                        let data = {
                            formData: formData
                        }
                        console.log(data);
                        addPeople(data).then((res) => {
                            if(res.code === 200){
                                addStaffDialogVisible.value = false;
                                ElNotification({
                                    title: 'OK!',
                                    message: '添加成功',
                                    duration: 1000,
                                    position: 'bottom-right',
                                    type: 'success',
                                });

                                formData.peopleNum = "";
                                formData.peopleName = "";
                                formData.position = "";
                                formData.classNum = "";

                                selectStaffBtnClick();
                            }else{
                                ElNotification({
                                    title: 'OK!',
                                    message: '添加失败请检查网络或已添加人员',
                                    duration: 1000,
                                    position: 'bottom-right',
                                    type: 'warning',
                                });
                                console.log(res);
                            }
                        },(error)=>{
                            console.log(error);
                        });
                        break;
                    case modeEnum.changeMode:
                        let changeData =
                        {
                            id: formData.id,
                            position: formData.position,
                            classNum: formData.classNum
                        }

                        console.log(changeData);

                        updatePeople(changeData).then((res) => {
                            if(res.code === 200){
                                addStaffDialogVisible.value = false;
                                ElNotification({
                                    title: 'OK!',
                                    message: '编辑成功',
                                    duration: 1000,
                                    position: 'bottom-right',
                                    type: 'success',
                                });
                                formData.id = -1;
                                formData.peopleNum = "";
                                formData.peopleName = "";
                                formData.position = "";
                                formData.classNum = "";

                                selectStaffBtnClick();

                            }else{
                                console.log(res);
                            }
                        },(error)=>{
                            console.log(error);
                        });
                        break;
                }

            }
        });
    }catch(err){
        console.log(err);
    }
}
let loading = computed(()=>{
    return store.state.loading;
});
let selectStaffBtnClick = debounce(()=>{
    let data = selectStaffObj;
    //是工班必须传工班否则会查询到所有的
    if(staffInfo.value.jurisdiction === 1){
        data.classNum = staffInfo.value.userNum;
    }

    selectPeople(data).then((res) => {
        if(res.code === 200){
            peopleInfoList.length = 0;
            peopleInfoList.push(...res.peopleInfoList);
        }else{
            console.log(res);
        }
    },(error)=>{
        console.log(error);
    });
},500);

watch(addStaffDialogVisible,(newValue)=>{
    if(newValue === false){
        formData.id = -1;
        formData.peopleName = "";
        formData.peopleNum = "";
        formData.position = "";
        formData.classNum = "";
    }
});

</script>

<style scoped lang="scss">
.staff-management-box{
    padding: 10px;
    .header-box{
        position: relative;
        padding-bottom: 10px;
        display: flex;
        &>*{
            margin-right: 5px;
        }
        .el-input{
            width: 250px
        }
        .left{
            position: absolute;
            right:10px
        }
    }
    .center-box{
        width: 100%;
        height: calc(100vh - 120px);
        overflow: auto;
        .el-link{
            margin-left:10px;
        }
    }
}
</style>
